﻿using System.Threading;
using System.Threading.Tasks;

namespace OmniKits.Async
{
    public abstract class RunJobAsync<T> : IRunJobAsync
        where T : class, ICanStartAsync, ICanWaitAsync
    {
        internal volatile T _Job;
        protected T Job => _Job;

        protected abstract T GetJob();

        protected virtual async Task<bool> RunAsync(bool wait)
        {
            var old = _Job;
            if (old != null)
            {
                await old.StartAsync();
                if (wait)
                    await old.WaitAsync();
                return false;
            }

            var job = GetJob();
            old = Interlocked.CompareExchange(ref _Job, job, null);
            if (old != null)
            {
                await old.StartAsync();
                if (wait)
                    await old.WaitAsync();
                return false;
            }

            try
            {
                await job.StartAsync();
                if (wait)
                    await old.WaitAsync();
                return true;
            }
            catch
            {
                Interlocked.CompareExchange(ref _Job, null, job);
                throw;
            }
        }

        public virtual Task<bool> StartAsync()
            => RunAsync(false);
        public virtual Task<bool> RunAsync()
            => RunAsync(true);

        public virtual async Task<bool> WaitAsync()
        {
            var job = _Job;
            if (job == null)
                return false;
            return await job.WaitAsync();
        }
    }
    public abstract class RunJobCanStopAsync<T> : RunJobAsync<T>, IRunJobCanStopAsync
        where T : class, ICanStartAsync, ICanWaitAsync, ICanStopAsync
    {
        public virtual async Task<bool> StopAsync()
        {
            var job = _Job;
            if (job == null)
                return false;
            job = Interlocked.Exchange(ref _Job, null);
            if (job == null)
                return false;

            try
            {
                await job.StopAsync();
                return true;
            }
            catch
            {
                Interlocked.CompareExchange(ref _Job, job, null);
                throw;
            }
        }
    }
}
